package com.ruoyi.training.service.impl;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.training.domain.ExamQuestion;
import com.ruoyi.training.domain.ExamQuestionOption;
import com.ruoyi.training.mapper.ExamQuestionMapper;
import com.ruoyi.training.mapper.ExamQuestionOptionMapper;
import com.ruoyi.training.service.IExamQuestionService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 课程题目管理Service业务层处理
 *
 * @author wng
 * @date 2024-08-04
 */
@Service
public class ExamQuestionServiceImpl implements IExamQuestionService {
    @Resource
    private ExamQuestionMapper examQuestionMapper;
    @Resource
    private ExamQuestionOptionMapper examQuestionOptionMapper;

    /**
     * 查询课程题目管理
     *
     * @param id 课程题目管理主键
     * @return 课程题目管理
     */
    @Override
    public ExamQuestion selectExamQuestionById(Long id) {
        return examQuestionMapper.selectExamQuestionById(id);
    }

    /**
     * 查询课程题目管理列表
     *
     * @param examQuestion 课程题目管理
     * @return 课程题目管理
     */
    @Override
    public List<ExamQuestion> selectExamQuestionList(ExamQuestion examQuestion) {
        List<ExamQuestion> examQuestions = examQuestionMapper.selectExamQuestionList(examQuestion);
        examQuestions.forEach(item -> {
            ExamQuestionOption option = new ExamQuestionOption();
            option.setQuestionId(item.getId());
            item.getParams().put("options", examQuestionOptionMapper.selectExamQuestionOptionList(option));
        });
        return examQuestions;
    }

    /**
     * 新增课程题目管理
     *
     * @param examQuestion 课程题目管理
     * @return 结果
     */
    @Override
    public int insertExamQuestion(ExamQuestion examQuestion) {
        examQuestion.setCreateTime(DateUtils.getNowDate());
        int i = examQuestionMapper.insertExamQuestion(examQuestion);
        if (i > 0) {
            List<ExamQuestionOption> options = JSON.parseArray(JSON.toJSONString(examQuestion.getParams().get("options")), ExamQuestionOption.class);
            examQuestionOptionMapper.insertExamQuestionOptionBatch(new HashMap<String, Object>() {{
                options.forEach(item -> item.setQuestionId(examQuestion.getId()));
                put("options", options);
            }});
        }
        return i;
    }

    /**
     * 批量新增课程题目
     */
    @Override
    @Transactional
    public void insertExamQuestionBatch(List<ExamQuestion> examQuestionList) {
        Long chapterId = 0L;
        Long curriculumId = 0L;
        if (examQuestionList != null && !examQuestionList.isEmpty()) {
            ExamQuestion examQuestion = examQuestionList.get(0);
            chapterId = examQuestion.getChapterId();
            curriculumId = examQuestion.getCurriculumId();
        } else {
            throw new ServiceException("没有题目");
        }
        Map<String, List<ExamQuestionOption>> optionsMap = new HashMap<>(10);
        List<ExamQuestionOption> allOptions = new ArrayList<>(10);
        String batchId = RandomStringUtils.random(8, true, true);
        examQuestionList.forEach(item -> {
            item.setAddFlag(RandomStringUtils.random(6, true, true));
            item.setBatchId(batchId);
            optionsMap.put(item.getAddFlag(), JSON.parseArray(JSON.toJSONString(item.getParams().get("options")), ExamQuestionOption.class));
        });
        //批量新增题目
        examQuestionMapper.insertExamQuestionBatch(new HashMap<String, Object>() {{
            put("examQuestions", examQuestionList);
        }});

        //将上面添加过的题目查询出来，以addFlag分组，然后分别将不同addFlag下的选项集合赋值题目id，最后批量添加选项
        Map<String, List<ExamQuestion>> collect = examQuestionMapper.selectExamQuestionList(new ExamQuestion(curriculumId, chapterId, batchId)).stream().collect(Collectors.groupingBy(ExamQuestion::getAddFlag));
        collect.forEach((key, value) -> {
            optionsMap.get(key).forEach(item -> {
                item.setQuestionId(value.get(0).getId());
            });
            allOptions.addAll(optionsMap.get(key));
        });

        examQuestionOptionMapper.insertExamQuestionOptionBatch(new HashMap<String, Object>() {{
            put("options", allOptions);
        }});

    }

    /**
     * 修改课程题目管理
     *
     * @param examQuestion 课程题目管理
     * @return 结果
     */
    @Override
    public int updateExamQuestion(ExamQuestion examQuestion) {
        examQuestion.setUpdateTime(DateUtils.getNowDate());
        int i = examQuestionMapper.updateExamQuestion(examQuestion);
        if (i > 0) {
            List<ExamQuestionOption> options = JSON.parseArray(JSON.toJSONString(examQuestion.getParams().get("options")), ExamQuestionOption.class);
            //删除题目已有选项
            examQuestionOptionMapper.deleteExamQuestionOptionByQuestionId(new Long[]{examQuestion.getId()});
            //新增选项
            examQuestionOptionMapper.insertExamQuestionOptionBatch(new HashMap<String, Object>() {{
                options.forEach(item -> item.setQuestionId(examQuestion.getId()));
                put("options", options);
            }});
        }
        return i;
    }

    /**
     * 批量删除课程题目管理
     *
     * @param ids 需要删除的课程题目管理主键
     * @return 结果
     */
    @Override
    public int deleteExamQuestionByIds(Long[] ids) {
        int i = examQuestionMapper.deleteExamQuestionByIds(ids);

        //批量删除题目下选项
        examQuestionOptionMapper.deleteExamQuestionOptionByQuestionId(ids);

        return i;
    }

    /**
     * 删除课程题目管理信息
     *
     * @param id 课程题目管理主键
     * @return 结果
     */
    @Override
    public int deleteExamQuestionById(Long id) {
        return examQuestionMapper.deleteExamQuestionById(id);
    }
}
